package com.beiming.moudle.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beiming.moudle.auth.dao.CustomerUserDao;
import com.beiming.moudle.auth.entity.CustomerUserEntity;
import com.beiming.moudle.auth.service.CustomerUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class CustomerUserServiceImpl extends ServiceImpl<CustomerUserDao, CustomerUserEntity> implements CustomerUserService {
    @Autowired
    private CustomerUserDao customerUserDao;

    @Override
    public CustomerUserEntity findByUsername(String username) {
        QueryWrapper<CustomerUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name",username);
        return getOne(queryWrapper);

    }

    //12小时后失效
    private final static int EXPIRE = 12;

    @Override
    public String createToken(CustomerUserEntity user) {
        //用UUID生成token
        String token = UUID.randomUUID().toString();
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        //过期时间
        LocalDateTime expireTime = now.plusHours(EXPIRE);
        //保存到数据库
        user.setLoginTime(now);
        user.setExpireTime(expireTime);
        user.setToken(token);
        customerUserDao.updateById(user);
        return token;
    }

    @Override
    public void logout(String token) {
        QueryWrapper<CustomerUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token",token);
        CustomerUserEntity customerUserEntity = getOne(queryWrapper);
        //用UUID生成token
//        token = UUID.randomUUID().toString();
        token = "";
        //修改用户的token使原本的token失效，前端需配合将token清除
        customerUserEntity.setToken(token);
        customerUserDao.updateById(customerUserEntity);

    }

    @Override
    public CustomerUserEntity findByToken(String token) {
        QueryWrapper<CustomerUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token",token);
        return getOne(queryWrapper);
    }

    @Override
    public int addCustomerUser(CustomerUserEntity customerUserEntity) {

        return   customerUserDao.insert(customerUserEntity);
    }

    @Override
    public int getUserStatus(int id) {
        QueryWrapper<CustomerUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id",id);
        CustomerUserEntity customerUserEntity=  customerUserDao.selectOne(queryWrapper);
        return customerUserEntity.getUserStats();
    }

    @Override
    public int updateCustomerStatus(CustomerUserEntity customerUserEntity) {
        return customerUserDao.updateById(customerUserEntity);
    }
}
